//
//  MainViewController.m
//  One
//
//  Created by mac on 16-5-19.
//  Copyright (c) 2016年 mac. All rights reserved.
//

#import "MainViewController.h"
#import "SCVView.h"
#import "NetIsReachabitity.h"
#import "HPObject.h"
#import "MainViewReqest.h"
#import "MonthViewController.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import <BaiduMapAPI_Radar/BMKRadarComponent.h>
#import <BaiduMapAPI_Map/BMKMapView.h>

@interface MainViewController ()<UIScrollViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>
{
    NSArray *hpObjectArray;
    int currentPageNum;
    BMKLocationService *_locService;
    BMKGeoCodeSearch *_search;
}
@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [NOTI_CENTER addObserver:self selector:@selector(notiMethod:) name:@"mainView" object:nil];
    [NOTI_CENTER addObserver:self selector:@selector(reachability:) name:@"reach" object:nil];
    [NetIsReachabitity networkIsReachability];

    [MainViewReqest requestMainViewData];
    


    _search = [[BMKGeoCodeSearch alloc] init];
    _search.delegate = self;
    _locService = [[BMKLocationService alloc] init];
    _locService.delegate = self;
    [_locService startUserLocationService];
}


#pragma mark -布局主页面
- (void)layoutMainView
{
    _mainScrollView.contentSize = CGSizeMake((WIDTH) * 10, HEIGHT - 64-120);
    _mainScrollView.pagingEnabled = YES;
    _mainScrollView.delegate = self;
    _mainScrollView.userInteractionEnabled = YES;
    [self removeMainSCVSubview];
    
    for ( int i = 0; i < 10; i ++ ) {
        
        __block SCVView *showView = nil;
        if (hpObjectArray) {
            HPObject *hpObj = hpObjectArray[i];
            if (i == 0) {
                hpObj.isFirst = YES;
                _praisenumLabel.text = [NSString stringWithFormat:@"%d",hpObj.praisenum];
                hpObj.cityName = _cityName;
                }
                showView = [[SCVView alloc]initWithHpObj:hpObj];
            }
        else
            showView = [[SCVView alloc]initWithHpObj:nil];
        
        showView.frame = CGRectMake((WIDTH) * i +10, 0, WIDTH, HEIGHT - 64-120);
        
        [_mainScrollView addSubview:showView];
    }
    
    
}

#pragma mark -获取到数据通知时间
- (void)notiMethod:(NSNotification *)noti
{
    hpObjectArray = noti.object;
    [self layoutMainView];
}

#pragma mark -检查是否连着网络
- (void)reachability:(NSNotification *)noti
{
    UIAlertController *alert = [noti object];
    if (alert) {
        [self presentViewController:alert animated:YES completion:nil];
        [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timeMethod:) userInfo:alert repeats:NO];
    }
    else
        [MainViewReqest requestMainViewData];
}

#pragma mark -删除主页scv上所有的姿势图
- (void)removeMainSCVSubview
{
    NSArray *subViewArr = [_mainScrollView subviews];
    [subViewArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
}

#pragma mark -无网络提示框自动消失
- (void)timeMethod:(NSTimer *)timer
{
    UIAlertController *aler = (UIAlertController *)[timer userInfo];

    [aler dismissViewControllerAnimated:YES completion:nil];
    aler = nil;

}

#pragma mark -按钮点击事件

- (IBAction)diaryButtonClick:(UIButton *)sender {
}


- (IBAction)likeButtonClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (hpObjectArray) {
        HPObject *object = hpObjectArray[currentPageNum];
        
        object.isPraise = sender.isSelected;
        
        if (sender.isSelected) {
            object.praisenum +=  1;

        }
        else
            object.praisenum -= 1;
        
        _praisenumLabel.text = [NSString stringWithFormat:@"%d",object.praisenum];
    }
}

- (IBAction)shareButtonClick:(id)sender {
    
    NSMutableDictionary *shareParems = [NSMutableDictionary dictionary];
    [shareParems SSDKSetupShareParamsByText:@"test"
                                     images:nil
                                        url:nil
                                      title:@"title"
                                       type:SSDKContentTypeAuto];
    
    [ShareSDK showShareActionSheet:nil
                             items:nil
                       shareParams:shareParems
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   switch (state) {
                       case SSDKResponseStateSuccess:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       case SSDKResponseStateFail:
                       {
                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                           message:[NSString stringWithFormat:@"%@",error]
                                                                          delegate:nil
                                                                 cancelButtonTitle:@"OK"
                                                                 otherButtonTitles:nil, nil];
                           [alert show];
                           break;
                       }
                       default:
                           break;
                   }
               }];
}

#pragma mark -UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    currentPageNum = scrollView.contentOffset.x/WIDTH;
    if (hpObjectArray) {
        
        HPObject *hpObj = hpObjectArray[currentPageNum];
        
        _praisButton.selected = hpObj.isPraise;
        _praisenumLabel.text = [NSString stringWithFormat:@"%d",hpObj.praisenum];
        
    }

}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x >= (WIDTH * 9 + WIDTH/4)) {
        
        HPObject *hpObj = hpObjectArray[0];
        NSString *date = hpObj.last_update_date;
        NSArray *dateArr = [date componentsSeparatedByString:@"-"];
        int year = [dateArr[0] intValue];
        int month = [dateArr[1] intValue];
        MonthViewController *monthView = [[MonthViewController alloc]init];
        
        int monthCount = [self MonthGoesByWithCurrentYear:year CurrentMonth:month];
        monthView.monthCount = monthCount;
        monthView.currentYear =year;
        monthView.currentMonth = month;
        
        [self.navigationController pushViewController:monthView animated:YES];
    }
    
}

#pragma mark -计算总共期数
- (int)MonthGoesByWithCurrentYear:(int)year CurrentMonth:(int)month
{

    int goesMonth = 3 + (year - 2013)*12 + month;
    return goesMonth;
}

#pragma mark -BMKLocationServiceDelegate
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    CLLocationCoordinate2D pt = userLocation.location.coordinate;
//    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){39.915, 116.404};
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[
    BMKReverseGeoCodeOption alloc]init];
    reverseGeoCodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [_search reverseGeoCode:reverseGeoCodeSearchOption];
    if(flag)
    {
      NSLog(@"反geo检索发送成功");
    }
    else
    {
      NSLog(@"反geo检索发送失败");
    }
    [_locService stopUserLocationService];
}

- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSLog(@">>>%@",result.addressDetail.city);
    _cityName = result.addressDetail.city;
    [self layoutMainView];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
